<template>
	<view class="page-login">
		<!-- 顶部渐变背景 -->
		<view class="top-gradient"></view>

		<!-- 关闭按钮
		<view class="close-btn">
			<u-icon size="24" name="close"></u-icon>
		</view> -->

		<!-- 标题区域 -->
		<view class="title-container">
			<text class="hello-text">你好，</text>
			<text class="welcome-text">欢迎来到理康养老</text>
		</view>

		<!-- 登录表单区域 -->
		<view class="form-container">
			<!-- 账号输入框 -->
			<view class="input-item">
				<u--input v-model="userInfo.phoneNum" type="number" border="none" placeholder="请输入账号"></u--input>
			</view>

			<!-- 验证码输入框 (样式模拟密码框) -->
			<view class="input-item">
				<u--input v-model="userInfo.phoneCode" type="password" border="none" maxlength="6"
					placeholder="请输入密码"></u--input>
				<!-- 隐藏获取验证码按钮 -->
				<!-- <u-tag @click="getCodeClick" :text="codetext" plain type="warning" shape="circle"></u-tag> -->
			</view>

			<!-- 登录按钮 -->
			<button class="login-btn" type="primary" @tap="login">登录</button>
		</view>

		<!-- 协议区域 -->
		<view class="protocol-container flex items-center">
			<view @tap="onAgreePrivateProtocol" class="checkbox">
				<u-icon v-if="privateAgree" size="18" color="#ff7d00" name="checkmark-circle-fill"></u-icon>
				<u-icon v-else size="18" name="checkmark-circle"></u-icon>
			</view>
			<text @tap="onAgreePrivateProtocol" class="protocol-text">我已阅读并同意养老</text>
			<text class="link" @tap="linkToUserAgreement">《用户服务协议》</text>
			<text class="protocol-text">及</text>
			<text class="link" @tap="linkToPrivacyTreaty">《隐私政策》</text>
		</view>

		<!-- 版本信息 -->
		<view v-if="version" class="version">{{ 'v' + version }}</view>
	</view>
</template>

<script>
// #ifdef H5
import { PhoneNumberServer } from '@/utils/numberAuth-web-sdk.js';
const phoneNumberServer = new PhoneNumberServer();
// #endif

import {
	apiLogin, apiGetUserList
} from '@/request/api.js';

export default {
	data() {
		return {
			version: '',
			userInfo: {
				phoneNum: '13426374937',
				phoneCode: '123456',
			},
			privateAgree: false,
			isSend: true,
			codetext: '获取验证码',
			countdown: 60,
		};
	},
	onShow() { },
	onLoad(option) {
		// 检查是否已经登录
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo && userInfo.hasLogin && userInfo.token) {
			// 已经登录，直接跳转到首页
			uni.switchTab({
				url: '../home/index'
			});
		}
	},
	methods: {
		//	获取验证码
		getCodeClick() {
			uni.hideKeyboard();
			//	获取验证码点击状态
			if (!this.isSend) return;
			if (this.userInfo.phoneNum.length == 0) {
				uni.showToast({
					icon: 'none',
					title: '手机号码不能为空',
					duration: 1500
				});
				return;
			} else if (!this.$tools.phoneReg(this.userInfo.phoneNum)) {
				uni.showToast({
					icon: 'none',
					title: '手机号码格式不正确',
					duration: 1500
				});
				return;
			}

			uni.showLoading({
				title: '发送中',
				mask: true
			})
			apiGetSmsCode({
				mobile: this.userInfo.phoneNum
			}).then((res) => {
				uni.hideLoading();
				if (res.code == 0) {
					uni.showToast({
						title: '发送成功',
						icon: 'success'
					})
					this.isSend = false;
					this.startTimeOut();
				}
			}).catch((err) => {
				uni.showToast({
					title: '发送失败',
					icon: 'error'
				})
				this.isSend = true;
				uni.hideLoading();
			});
		},
		// 验证码倒计时
		startTimeOut() {
			if (this.countdown == 0) {
				this.isSend = true;
				this.codetext = '重新获取';
				this.countdown = 60;
				return;
			} else {
				this.isSend = false;
				this.codetext = this.countdown + 's 重新获取';
				this.countdown--;
			}
			setTimeout(() => {
				this.startTimeOut();
			}, 1000);
		},
		// 获取用户详细信息
		async getUserDetailInfo(token) {
			try {
				// 临时保存token以供API调用使用
				const tempUserInfo = {
					token: token,
					hasLogin: true
				};
				uni.setStorageSync('userInfo', tempUserInfo);

				// 调用用户列表API获取详细信息
				const userListResponse = await apiGetUserList({
					uid: '1' // 根据API文档使用固定值，实际可能需要从登录响应获取
				});

				if (userListResponse.code === 0 && userListResponse.data && userListResponse.data.info) {
					const userDetail = userListResponse.data.info;
					const userList = userListResponse.data.data || [];

					// 构建完整的用户信息
					const completeUserInfo = {
						// 基础登录信息
						token: token,
						hasLogin: true,

						// 用户详细信息
						uid: userDetail.id,
						name: userDetail.name,
						nickname: userDetail.nickname,//(没有)
						phone: userDetail.phone,
						email: userDetail.email,

						// 个人信息
						sex: userDetail.sex,
						birthday: userDetail.birthday,
						marry: userDetail.marry,
						contact: userDetail.contact,
						contact_phone: userDetail.contact_phone,

						// 身份信息
						id_num: userDetail.id_num,
						id_back: userDetail.id_back,
						id_face: userDetail.id_face,

						// 地址信息
						province: userDetail.province,
						city: userDetail.city,
						area: userDetail.area,

						// 工作信息
						part: userDetail.part,
						position: userDetail.position,
						level: userDetail.level,

						// 健康信息(没有)
						medical_history: userDetail.medical_history,
						allergy_history: userDetail.allergy_history,

						// 系统信息
						status: userDetail.status,
						auth_ids: userDetail.auth_ids, //(没有)
						create_time: userDetail.create_time,//(没有)
						update_time: userDetail.update_time,

						// 其他
						photo: userDetail.photo,
						desc: userDetail.desc,
						classes: userDetail.classes,//(没有)

						// 用户列表（如果需要）
						userList: userList,

						// 统计信息
						num: userDetail.num,//(没有)
						ip: userDetail.ip,//(没有)
						position_time: userDetail.position_time//(没有)
					};

					// 保存完整的用户信息
					uni.setStorageSync('userInfo', completeUserInfo);
					uni.setStorageSync('hasLogin', true);

					console.log('用户详细信息获取成功:', completeUserInfo);
					return true;
				} else {
					console.error('获取用户详细信息失败:', userListResponse);
					return false;
				}
			} catch (error) {
				console.error('获取用户详细信息出错:', error);
				return false;
			}
		},
		// 登录
		async login() {
			if (this.userInfo.phoneNum == '') {
				uni.showToast({
					icon: 'none',
					title: '请输入手机号'
				});
				return;
			} else if (!this.$tools.phoneReg(this.userInfo.phoneNum)) {
				uni.showToast({
					icon: 'none',
					title: '手机号码错误',
					duration: 1500
				});
				return;
			} else if (this.userInfo.phoneCode == '' || this.userInfo.phoneCode.length < 6) {
				uni.showToast({
					icon: 'none',
					title: '请输入验证码',
					duration: 1500
				});
				return;
			} else if (!this.privateAgree) {
				uni.showToast({
					icon: 'none',
					title: '请先阅读并同意相关协议',
					duration: 1500
				});
				return;
			}

			uni.showLoading({
				title: '登录中',
				mask: true
			})
			try {
				// 调用登录API
				const loginData = {
					phone: this.userInfo.phoneNum,
					password: this.userInfo.phoneCode
				};

				const response = await apiLogin(loginData);

				if (response.code === 0) {
					// 登录成功，获取用户详细信息
					const userListResponse = await this.getUserDetailInfo(response.data.token);

					if (userListResponse) {
						uni.hideLoading();
						uni.showToast({
							title: response.msg || '登录成功',
							icon: 'success'
						});
						// 跳转到首页
						setTimeout(() => {
							uni.switchTab({
								url: '../home/index'
							});
						}, 1500);
					} else {
						uni.hideLoading();
						// 如果获取用户信息失败，仍然允许登录但使用基础信息
						const basicUserInfo = {
							token: response.data.token,
							phone: response.data.phone,
							flag: response.data.flag,
							hasLogin: true,
							uid: response.data.uid || '33897' // 使用返回的uid或默认值
						};
						uni.setStorageSync('userInfo', basicUserInfo);
						uni.setStorageSync('hasLogin', true);

						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});

						setTimeout(() => {
							uni.switchTab({
								url: '../home/index'
							});
						}, 1500);
					}
				}
			} catch (error) {
				uni.hideLoading();
				console.error('登录失败:', error);
				// 错误信息已经在request.js中通过toast显示了
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});

				setTimeout(() => {
					uni.switchTab({
						url: '../home/index'
					});
				}, 1500);
			}
		},

		// 同意协议
		onAgreePrivateProtocol() {
			this.privateAgree = !this.privateAgree
		},

		// 隐私协议
		linkToPrivacyTreaty() {
			// 根据不同平台显示不同隐私注册
			if (uni.getSystemInfoSync().platform == 'ios') {
				uni.navigateTo({
					url: '../webview/webview?url=http://www.xxxx.com/privacyPolicy.html'
				})
			} else {
				uni.navigateTo({
					url: '../webview/webview?url=http://www.xxxx.com/userPrivacyPolicy.html'
				})
			}
		},

		// 用户协议
		linkToUserAgreement() {
			uni.navigateTo({
				url: '../webview/webview?url=http://www.xxxx.com/userAgr.html'
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.page-login {
	height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	background-color: #ffffff;
	padding: 0 50rpx;
	position: relative;
}

/* 顶部渐变背景 */
.top-gradient {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 400rpx;
	flex-shrink: 0;
	aspect-ratio: 1/1;
	border-radius: 1000px;
	background: linear-gradient(256deg, #FF4856 11.85%, #FF6F1C 77.55%);
	filter: blur(190px);
	z-index: 0;
}

/* 关闭按钮 */
.close-btn {
	position: absolute;
	top: 40rpx;
	left: 30rpx;
	z-index: 2;
}

/* 标题样式 */
.title-container {
	margin-top: 190rpx;
	margin-bottom: 60rpx;
	text-align: left;
	/* 文字左对齐 */
	position: relative;
	z-index: 1;
	width: 100%;
	/* 确保宽度充满父容器 */
	box-sizing: border-box;
	/* 确保内边距不会增加总宽度 */

}

.hello-text {
	color: #000d3d;
	font-family: "PingFang SC";
	font-size: 27px;
	font-style: normal;
	font-weight: 600;
	line-height: normal;
}

.welcome-text {
	// font-size: 40rpx;
	// font-weight: bold;
	// color: #333333;
	display: block;
	// line-height: 1.5;
	color: #000d3d;
	font-family: "PingFang SC";
	font-size: 27px;
	font-style: normal;
	font-weight: 600;
	line-height: normal;
}

/* 表单容器 */
.form-container {
	width: 100%;
	position: relative;
	z-index: 1;
}

/* 输入框样式 */
.input-item {
	height: 90rpx;
	border-radius: 10rpx;
	background-color: #ffffff;
	border: 1px solid #eeeeee;
	padding: 0 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.u-input {
	font-size: 30rpx;
	color: #333333;
	height: 90rpx;
	width: 100%;
	/* 让输入框占满宽度 */
}

/* 登录按钮 */
.login-btn {
	width: 100%;
	height: 90rpx;
	flex-shrink: 0;
	border-radius: 12px;
	background: linear-gradient(256deg, #FF4856 11.85%, #FF6F1C 77.55%);
	color: #ffffff;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	margin-top: 60rpx;
	/* 增加上边距，使按钮更靠下 */
	line-height: 90rpx;
}

/* 协议区域 */
.protocol-container {
	margin-top: 500rpx;
	/* 增加上边距，使协议区域更靠下 */
	font-size: 24rpx;
	color: #666666;
	position: relative;
	z-index: 1;
	flex-wrap: wrap;
	justify-content: center;
}

.checkbox {
	margin-top: 3rpx;
	margin-right: 10rpx;
}

.protocol-text {
	margin: 0 4rpx;
}

.link {
	color: #ff7d00;
	margin: 0 4rpx;
}

/* 版本信息 */
.version {
	margin-top: 60rpx;
	font-size: 24rpx;
	color: #999999;
	position: relative;
	z-index: 1;
}
</style>